package 多线程.消费者生产者;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class BlockQ {
    public static void main(String[] args) throws InterruptedException {
        BlockingQueue<String> bq = new ArrayBlockingQueue(10);
        Producer p = new Producer(bq);
        Consumer c = new Consumer(bq);
        new Thread(()->{
            try {
                p.produce();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"生产者").start();
        new Thread(()->{
            try {
                c.consume();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"消费者").start();
    }
}

class Producer{
    BlockingQueue<String> q;
    public Producer(BlockingQueue<String> q){
        this.q = q;
    }
    public void produce() throws InterruptedException {
        int count = 1;
        while(true){
            String msg = "物品"+count++;
            q.add(msg);
            System.out.println(Thread.currentThread()+"放入"+msg);
            Thread.sleep(1000);
        }
    }
}

class Consumer{
    BlockingQueue<String> q;
    public Consumer(BlockingQueue<String> q){
        this.q = q;
    }
    public void consume() throws InterruptedException {
        while(true){
            String take = q.take();
            System.out.println(Thread.currentThread()+"拿出"+take);
            Thread.sleep(1000);
        }
    }
}
